﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Mr.HttpBodyWrapper
{
    public class FileParameter : IFileParameter
    {
        public FileParameter()
            : this(string.Empty, string.Empty, null)
        { }

        public FileParameter(string name, string fileName, byte[] data)
        {
            this.Name = name;
            this.FileData = data;
            this.FileName = fileName;

            this.ContentType = this.GetContentTypeFromFileName(fileName);
        }

        public string Name { get; private set; }

        public string FileName { get; private set; }

        public byte[] FileData { get; private set; }

        #region IParameter Members

        public string ToParamString()
        {
            if (this.FileData != null)
            {
                return Encoding.UTF8.GetString(this.FileData);
            }
            else return string.Empty;
        }

        public string ContentType { get; private set; }

        #endregion

        private string GetContentTypeFromFileName(string fileName)
        {
            int pos = fileName.LastIndexOf('.');
            string retType = "text/plain";
            if (pos != -1)
            {
                string type = fileName.Substring(pos + 1);
                switch (type.ToLower())
                {
                    case "jpg":
                        retType = "image/jpeg";
                        break;
                    case "gif":
                        retType = "image/gif";
                        break;
                    case "png":
                        retType = "image/png";
                        break;
                    case "txt":
                        retType = "text/plain";
                        break;
                }
            }
            return retType;
        }
    }
}
